var type = "1";
var count = 0;
var newsTpl = "{{# layui.each(d.newsData, function(index, item){ }}<tr itemid='{{item.NEWS_ID}}'><td><input type=\"checkbox\" name=\"checked\" lay-skin=\"primary\" lay-filter=\"choose\"></td><td>{{item.NEWS_NAME}}</td><td>{{item.CREATE_USER_NAME}}</td><td>{{item.CREATE_TIME}}</td><td><form class='layui-form' action=''><div class='layui-input-block'><input {{# if ( '1'==item.VALID_TAG){ }} checked= 'true'{{# } }} name='open' lay-skin='switch' lay-filter='isValid' lay-text='是|否' type='checkbox' itemid='{{item.NEWS_ID}}'></div></form></td><td>{{item.LAST_CHANGE_USER_NAME}}</td><td>{{item.LAST_CHANGE_TIME}}</td><td><button class='layui-btn layui-btn-sm layui-btn-normal' onclick='editNews(\"{{item.NEWS_ID}}\")'><i class='layui-icon'>&#xe642;</i></button></td><td><button class='layui-btn layui-btn-sm layui-btn-danger' onclick='deleteNews(\"{{item.NEWS_ID}}\")'><i class='layui-icon'>&#xe640;</i></button></td></tr>{{# }); }}";
layui.use(['form','layer','jquery','laypage','element','laytpl'],function(){
	var form = layui.form,
		layer = layui.layer,
		laypage = layui.laypage,
		$ = layui.jquery,
		element = layui.element,
        laytpl = layui.laytpl;

    //校验登录状态
    if(isNotLogIn()){
        return;
    }

    /**
	 * by myself
     * @type {string}
     */
    element.tabChange('news_search',"0"); //切换到相应lay-id类型
    //获取新闻信息,默认获取最新动态
    getAllNewsInfo("0");
    element.on('tab(news_search)', function(data){
        var newType = $(this).attr("lay-id");
        if(newType==type){
            return;
        }
        type = newType;
        //重新加载一个表格
        getAllNewsInfo(newType);
    });

    //新闻展示与否的切换
    form.on('switch(isValid)', function(data){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        var isValid = this.checked ?"1":"0";
        var newsId = $(this).attr("itemid");
        //调用后台转换新闻展示与否的状态
        var index = layer.load(3);
        $.ajax({
            url:"/CivilAffairs/manager/changeValidTag",
            type:"post",
            data:{"isValid":isValid,"dataId":newsId,"dataType":"news"},
            dataType:"json",
            success:function(result){
                layer.close(index);
                if(checkResult(result)){
                    layer.msg(result.detail,{icon:6});
                }
            },
            error : function(result) {
                layer.close(index);
                console.log((this.checked?"展示":"不展示")+"新闻:"+result.status+","+result.statusMessage+",newsId:"+newsId);
                layer.msg("系统异常,请稍后重试",{icon:2});
            }
        });

    });

    //全选
    form.on('checkbox(selectAll)', function(data){
        var child = $(data.elem).parents('table').find('tbody input[name="checked"]:not([name="open"])');
        child.each(function(index, item){
            item.checked = data.elem.checked;
        });
        form.render('checkbox');
    });

    //添加文章
    //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
    $(window).one("resize",function(){
		$(".newsAdd_btn").click(function(){
            //校验登录状态
            if(isNotLogIn()){
                return;
            }
			var index = layui.layer.open({
				title : "添加文章",
				type : 2,
				content : "newsAdd.html",
				success : function(layero, index){
					setTimeout(function(){
						layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
							tips: 3
						});
					},500)
				}
			});
			layui.layer.full(index);
		});
	}).resize();

    var searchCount = 0;
    var newsName = "";
    //搜索
    $(".search_btn").click(function () {
        var searchName = $(".search_input").val();
        if(isNull(searchName)){
            layer.msg("请输入要搜索的新闻标题");
            return;
        }
        searchNameInfo(searchName);
    });

    function searchNameInfo(searchName,page,limit){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        page = isNull(page)?0:page;
        limit = isNull(limit)?10:limit;
        var index = layer.load(3);
        $.ajax({
            url : "/CivilAffairs/manager/getNewsByType",
            type : "post",
            data : {"newsType":type,"searchName":searchName,"page":page,"limit":limit},
            async : false,
            dataType : "json",
            success : function(result) {
                layer.close(index);
                if("0000"==result.status){
                    laytpl(newsTpl).render(result.data.data, function(html) {
                        $(".news_content").html(html);
                    });
                    //重新渲染
                    form.render('checkbox');
                    //需要重新加载分页
                    if(searchCount!=result.data.count || name != searchName){
                        searchCount = result.data.count;
                        newsName = searchName;
                        //分页组件
                        laypage.render({
                            elem: 'news-page'
                            ,count: result.data.count //数据总数，从服务端得到
                            ,layout: ['count', 'prev', 'page', 'next', 'limit', 'skip']
                            ,jump: function(obj, first){
                                //首次不执行
                                if(!first){
                                    searchNameInfo(searchName,obj.curr,obj.limit);
                                }
                            }
                        });
                    }
                }else{
                    var newsTypeName = getNesTypeNameById(type);
                    var detail = (isNull(type)||"0"==type)&&isNull(newsTypeName)?"":"在新闻类型[ "+newsTypeName+" ]中";
                    layer.msg(detail+"未查询到有关[ "+searchName+" ]的新闻",{icon:2});
                }

            },
            error:function(result){
                layer.close(index);
                reqError(result,"搜索服务信息异常");
            }
        });
    }

    //根据服务id获取服务名称
    function getNesTypeNameById(newsType){
        var nesTypeName = "";
        $("#news-type li").each(function () {
            if($(this).attr("lay-id")==newsType){
                nesTypeName = $(this).text();
            }
        });
        return nesTypeName;
    }

    //删除信息
    function deleteNews(newsId,isAllDel){
        if(isNotLogIn()||isNull(newsId)){
            return;
        }
        $.ajax({
            url:"/CivilAffairs/manager/deleteNews",
            type : "post",
            data : {"newsId":newsId},
            async : false,
            dataType : "json",
            success : function(result) {
                if("0000"==result.status){
                    layer.msg(result.detail,{icon:6});
                    //重非批量删除时重新加载表格
                    if(!isAllDel){
                        getAllNewsInfo(type);
                    }
                }else{
                    layer.msg(result.detail,{icon:2});
                }
            },
            error : function(result) {
                layer.close(index);
                console.log("管理员获取新闻异常:"+result.status+","+result.statusMessage);
                layer.msg("系统异常,请稍后重试",{icon:2});
            }
        });
    }

    //批量删除
    $(".batchDel").click(function(){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        var $checkbox = $('.news_content tr input[name="checked"]');
        var $checked = $('.news_content tr input[name="checked"]:checked');
        if($checkbox.is(":checked")){
            layer.confirm('确定删除选中的信息？',{icon:3, title:'提示信息'},function(index){
                var index = layer.msg('删除中，请稍候',{icon: 16,time:false,shade:0.8});
                //删除数据
                $checked.each(function(){
                    var optionId = $(this).parents("tr").attr("itemid");
                    deleteNews(optionId,true);
                });
                getAllNewsInfo(type);
                layer.close(index);
            })
        }else{
            layer.msg("请选择需要删除的信息");
        }
    });

    //判断回车
    $(document).keyup(function (e) {//捕获文档对象的按键弹起事件
        if (e.keyCode == 13) {
            $(".search_btn").click();
        }
    });

    //通过判断文章是否全部选中来确定全选按钮是否选中
    form.on("checkbox(choose)",function(data){
        var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="open"])');
        var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="open"]):checked')
        if(childChecked.length == child.length){
            $(data.elem).parents('table').find('thead input#selectAll').get(0).checked = true;
        }else{
            $(data.elem).parents('table').find('thead input#selectAll').get(0).checked = false;
        }
        form.render('checkbox');
    });
});

/**
 * 获取新闻内容
 * @param newsTyep 新闻类型
 */
function getAllNewsInfo(newsType,page,limit){
    //校验登录状态
    if(isNotLogIn()){
        return;
    }
    newsType = 0==newsType?"":newsType;
    page = isNull(page)?0:page;
    limit = isNull(limit)?10:limit;
    layui.use(["jquery","layer","laypage","laytpl","form"],function () {
        var laypage = layui.laypage
            ,laytpl = layui.laytpl
            ,layer = layui.layer
            ,form = layui.form
            ,$ = layui.$;
        var index = layer.load(3);
        $.ajax({
            url:"/CivilAffairs/manager/getNewsByType",
            type : "post",
            data : {"newsType":newsType,"page":page,"limit":limit},
            async : false,
            dataType : "json",
            success : function(result) {
                layer.close(index);
                if(checkResult(result)){
                    laytpl(newsTpl).render(result.data.data, function(html) {
                        $(".news_content").html(html);
                    });
                    //重新渲染
                    form.render('checkbox');
                    removeAllSel();
                    //需要重新加载分页
                    if(count!=result.data.count ||newsType != type){
                        count = result.data.count;
                        type = newsType
                        //分页组件
                        laypage.render({
                            elem: 'news-page'
                            ,count: result.data.count //数据总数，从服务端得到
                            ,layout: ['count', 'prev', 'page', 'next', 'limit', 'skip']
                            ,jump: function(obj, first){
                                //obj包含了当前分页的所有参数，比如：
                                //console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
                                //console.log(obj.limit); //得到每页显示的条数
                                //首次不执行
                                if(!first){
                                    console.log("not first");
                                    getAllNewsInfo(newsType,obj.curr,obj.limit);
                                }
                            }
                        });
                    }
                }
            },
            error : function(result) {
                layer.close(index);
                console.log("管理员获取新闻异常:"+result.status+","+result.statusMessage);
                layer.msg("系统异常,请稍后重试",{icon:2});
            }
        });
        layer.close(index);
    });
}


//编辑文章
function editNews(newsId){
    //校验登录状态
    if(isNotLogIn()){
        return;
    }
    if(isNull(newsId)){
        layui.layer.msg("获取要编辑的文章异常,请刷新页面重试");
        return;
    }
    var $ = layui.jquery;
    $(window).one("resize",function(){
        //编辑文章
        var index = layui.layer.open({
            title : "编辑新闻",
            type : 2,
            content : "newsAdd.html?newsId="+newsId,
            success : function(layero, index){
                setTimeout(function(){
                    layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        });
        layui.layer.full(index);
    }).resize();
}

/**
 * 删除新闻
 * @param newsId
 */
function deleteNews(newsId){
    //校验登录状态
    if(isNotLogIn()){
        return;
    }
    layui.use(["jquery","layer"],function () {
        var $ = layui.$
            ,layer = layui.layer;
        //询问框
        layer.confirm('确定删除新闻?', {
            btn: ['确定','取消'] //按钮
        }, function(){
            $.ajax({
                url:"/manager/deleteNews",
                type : "post",
                data : {"newsId":newsId},
                async : false,
                dataType : "json",
                success : function(result) {
                    if("0000"==result.status){
                        layer.msg(result.detail,{icon:6});
                        //重新加载表格
                        getAllNewsInfo(type);
                    }else{
                        layer.msg(result.detail,{icon:2});
                    }
                },
                error : function(result) {
                    layer.close(index);
                    console.log("管理员获取新闻异常:"+result.status+","+result.statusMessage);
                    layer.msg("系统异常,请稍后重试",{icon:2});
                }
            });
        });
    });
}
